package com.suneast.suneaststore.modules.shopcart;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.suneast.suneaststore.R;
import com.suneast.suneaststore.app.AccountManager;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.modules.goodsdetail.GoodsDetailFragment;
import com.suneast.suneaststore.modules.goodsdetail.GoodsHandler;
import com.suneast.suneaststore.modules.goodsdetail.SelectParameterDialog;
import com.suneast.suneaststore.modules.goodsdetail.event.ConfirmGoodsEvent;
import com.suneast.suneaststore.modules.goodsdetail.event.GotSpecsDataEvent;
import com.suneast.suneaststore.modules.shopcart.adapter.MultiShopCartAdapter;
import com.suneast.suneaststore.bean.shopcart.IdPosBean;
import com.suneast.suneaststore.bean.shopcart.ItemGoodsInShopCart;
import com.suneast.suneaststore.bean.shopcart.ItemShopGoodsList;
import com.suneast.suneaststore.bean.shopcart.MultipleItemShopCart;
import com.suneast.suneaststore.modules.shopcart.event.CartEmptyEvent;
import com.suneast.suneaststore.modules.shopcart.event.DeleteGoodsResult;
import com.suneast.suneaststore.modules.shopcart.event.EditCountEvent;
import com.suneast.suneaststore.modules.shopcart.event.EditGoodsEvent;
import com.suneast.suneaststore.modules.shopcart.event.GotShopCartList;
import com.suneast.suneaststore.modules.shopcart.event.ItemGoodsSelectResult;
import com.suneast.suneaststore.modules.shopcart.event.ItemSelectChange;
import com.suneast.suneaststore.modules.shopcart.event.SelectAllChange;
import com.suneast.suneaststore.modules.shopcart.event.UpdateResult;
import com.suneast.suneaststore.ui.customview.ZzCheckBox;
import com.suneast.suneaststore.ui.dialog.CancelConfirmDialog;
import com.suneast.suneaststore.ui.fragments.bottom.BottomItemFragment;
import com.suneast.suneaststore.util.log.LatteLogger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

public class ShopCartFragment extends BottomItemFragment implements CancelConfirmDialog.ConfirmBtnClickListener {
    @Override
    public @LayoutRes
    int setLayout() {
        return R.layout.fragment_shop_cart;
    }

    /**
     * 根据此标记 显示或隐藏返回按钮
     */
    private int type; //哪个界面跳转过来的?  0:主界面的购物车界面  1:商品详情界面跳转过来的

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        EventBus.getDefault().register(this);
        Bundle bundle = getArguments();
        if (bundle != null) {
            type = bundle.getInt("type", 0);
        }
    }

    private boolean isLazyInit = false;
    SparseArray<IdPosBean> goodsArray;
    SparseArray<IdPosBean> selectedGoodsArray;
    SparseArray<ItemGoodsInShopCart> editGoodsArray;

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        goodsArray = new SparseArray<>();
        selectedGoodsArray = new SparseArray<>();
        editGoodsArray = new SparseArray<>();
        initView();
        if (AccountManager.getSignState()) {
            ShopCartHandler.requestShopCartList();
        }
        isLazyInit = true;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (isLazyInit && !hidden) {
            ShopCartHandler.requestShopCartList();
        }
    }

    List<MultipleItemShopCart> multipleItemList;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotShopCartList(GotShopCartList event) {
        emptyCartTipLayout.setVisibility(View.GONE);
        editCB.setVisibility(View.VISIBLE);
        editCB.setChecked(false);
        gotoPayLayout.setVisibility(View.VISIBLE);
        refreshLayout.finishRefresh();
        editGoodsArray.clear();
        multipleItemList = convertToMultipleList(event.getList());
        adapter.setNewData(multipleItemList);
        totalPayTv.setText(String.format(getString(R.string.total_rmb),
                df.format(event.getTotalPrice())));
        actuallyPaidTv.setText(String.format(getString(R.string.actually_rmb),
                df.format(event.getRealPrice())));
        coinDiscountTv.setText(String.format(getString(R.string.deduction_rmb),
                df.format(event.getCoinPrice())));
        returnCoinTv.setText(String.format(getString(R.string.return_coin),
                df.format(event.getCoinRewardPrice())));
        selectedGoodsArray.clear();
        goodsArray.clear();
        for (int i = 0, length = multipleItemList.size(); i < length; i++) {
            MultipleItemShopCart item = multipleItemList.get(i);
            if (item.getItemType() == MultipleItemShopCart.GOODS) {
                if (item.getGoods().isSelected()) {
                    selectedGoodsArray.put(item.getGoods().getId(),
                            new IdPosBean(item.getGoods().getId(), i));
                }
                goodsArray.put(item.getGoods().getId(),
                        new IdPosBean(item.getGoods().getId(), i));
            }
        }
        setGoToPayBtn(selectedGoodsArray.size());
    }


    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.layout_goto_pay)
    LinearLayout gotoPayLayout;

    private DecimalFormat df;

    private void initView() {
        df = new DecimalFormat("0.00");
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener((@NonNull RefreshLayout refreshLayout) -> {
            if (AccountManager.getSignState()) {
                ShopCartHandler.requestShopCartList();
            }
        });
        if (type == 1) {
            toolbar.setNavigationIcon(R.drawable.ic_arrow_left_white);
            toolbar.setNavigationOnClickListener(v -> pop());
        }
        adapter = new MultiShopCartAdapter(new ArrayList<>());
        adapter.setOnItemChildClickListener((BaseQuickAdapter adapter, View view, int position) -> {
            MultipleItemShopCart item = (MultipleItemShopCart) adapter.getItem(position);
            if (item != null && item.getGoods() != null) {
                switch (view.getId()) {
                    case R.id.img_goods: {
                        GoodsDetailFragment fragment = new GoodsDetailFragment();
                        fragment.withId(item.getGoods().getGoodsId());
                        if (type == 0) {
                            getParentDelegate().start(fragment);
                        } else {
                            start(fragment);
                        }
                    }
                    break;
                    case R.id.tv_goods_intro_in_edit:
                    case R.id.img_arrow_down: {
                        LatteLogger.e(TAG, "goodsId = " + item.getGoods().getGoodsId());
                        SelectParameterDialog.setCartId(item.getGoods().getId());
                        GoodsHandler.requestSpecsData(item.getGoods().getGoodsId());
                    }
                }
            }
        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter.bindToRecyclerView(mRecyclerView);
    }

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.cb_edit_shop_cart)
    CheckBox editCB = null;
    @BindView(R.id.rv_shop_cart)
    RecyclerView mRecyclerView = null;
    MultiShopCartAdapter adapter;
    @BindView(R.id.layout_cart_empty_tip)
    LinearLayout emptyCartTipLayout;
    @BindView(R.id.total_pay_tv)
    TextView totalPayTv = null;
    @BindView(R.id.actually_paid_tv)
    TextView actuallyPaidTv = null;
    @BindView(R.id.coin_discount_tv)
    TextView coinDiscountTv = null;
    @BindView(R.id.return_coin_tv)
    TextView returnCoinTv = null;
    @BindView(R.id.btn_go_to_pay)
    Button gotoPayBtn;
    @BindView(R.id.delete_goods_layout)
    RelativeLayout deleteGoodsLayout;

    @OnClick({R.id.btn_go_to_pay, R.id.btn_delete, R.id.btn_move_to_interest})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_go_to_pay: {
                //跳转到账单界面
                if (selectedGoodsArray != null && selectedGoodsArray.size() > 0) {
                    BillConfirmFragment fragment = new BillConfirmFragment().withType(1);
                    if (type == 0) {//从主界面显示的购物车
                        getParentDelegate().start(fragment);
                    } else if (type == 1) {//从商品详情显示的购物车
                        start(fragment);
                    }
                } else {
                    Toast.makeText(_mActivity, "您勾选商品哦", Toast.LENGTH_SHORT).show();
                }
            }
            break;
            case R.id.btn_delete: {
                if (dialog == null) {
                    initDialog();
                }
                if (getFragmentManager() != null) {
                    dialog.show(getFragmentManager(), "");
                }
            }
            break;
            case R.id.btn_move_to_interest: {
                //todo 将勾选的商品加入关注列表
            }
            break;
        }
    }

    CancelConfirmDialog dialog = null;

    private void initDialog() {
        dialog = new CancelConfirmDialog();
        Bundle bundle = new Bundle();
        bundle.putString("content", "确认要从购物车删除吗?");
        dialog.setArguments(bundle);
        dialog.setListener(this);
    }

    @OnCheckedChanged({R.id.select_all_box, R.id.cb_edit_shop_cart})
    public void onCheckChange(CompoundButton checkBox, boolean isChecked) {
        switch (checkBox.getId()) {
            case R.id.select_all_box: {
                if (isChecked) {
                    selectedGoodsArray = goodsArray.clone();
                } else {
                    selectedGoodsArray.clear();
                }
                SelectAllChange event = new SelectAllChange(isChecked);
                EventBus.getDefault().post(event);
                //
            }
            break;
            case R.id.cb_edit_shop_cart: {
                if (isChecked) {
                    adapter.setSelectMode(Flag.SelectMode.EDIT);
                    checkBox.setText(getString(R.string.finish));
                    deleteGoodsLayout.setVisibility(View.VISIBLE);
                } else {
                    adapter.setSelectMode(Flag.SelectMode.SELECT);
                    checkBox.setText(getString(R.string.edit));
                    deleteGoodsLayout.setVisibility(View.GONE);
                }
            }
            break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEditItemSelectChange(ItemSelectChange event) {
        if (event.isChecked()) {
            selectedGoodsArray.put(event.getId(), goodsArray.get(event.getId()));
        } else {
            selectedGoodsArray.delete(event.getId());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onItemGoodsSelectResult(ItemGoodsSelectResult event) {
        if (event.getResult() == Flag.Result.SUCCEED) {
            if (event.getSelected() == 1) {
                selectedGoodsArray.put(event.getId(), goodsArray.get(event.getId()));
            } else {
                selectedGoodsArray.delete(event.getId());
            }
            totalPayTv.setText(String.format(getString(R.string.total_rmb),
                    df.format(event.getTotalPrice())));
            actuallyPaidTv.setText(String.format(getString(R.string.actually_rmb),
                    df.format(event.getRealPrice())));
            coinDiscountTv.setText(String.format(getString(R.string.deduction_rmb),
                    df.format(event.getCoinPrice())));
            returnCoinTv.setText(String.format(getString(R.string.return_coin),
                    df.format(event.getCoinRewardPrice())));
            setGoToPayBtn(event.getTotalCount());
        } else {
            ZzCheckBox cb = findCbById(event.getId());
            if (cb != null) {
                cb.setChecked(!cb.isChecked());
            }
        }
    }

    private void setGoToPayBtn(int size) {
        gotoPayBtn.setText(String.format(getString(R.string.settle_accounts_with_count),
                String.valueOf(size)));
    }

    private ZzCheckBox findCbById(int id) {
        List<ZzCheckBox> cbList = adapter.getCbList();
        for (int i = 0, length = cbList.size(); i < length; i++) {
            if (id == (Integer) cbList.get(i).getTag()) {
                return cbList.get(i);
            }
        }
        return null;
    }


    private List<MultipleItemShopCart> convertToMultipleList(ArrayList<ItemShopGoodsList> list) {
        ArrayList<MultipleItemShopCart> mList = new ArrayList<>();
        for (int i = 0, length = list.size(); i < length; i++) {
            MultipleItemShopCart shopBean = new MultipleItemShopCart(MultipleItemShopCart.SHOP,
                    list.get(i).getShopId(), list.get(i).getShopName());
            mList.add(shopBean);
            for (int j = 0, jLength = list.get(i).getItemList().size(); j < jLength; j++) {
                MultipleItemShopCart goodsBean = new MultipleItemShopCart(MultipleItemShopCart.GOODS,
                        list.get(i).getItemList().get(j));
                mList.add(goodsBean);
            }
        }
        return mList;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCartEmpty(CartEmptyEvent event) {
        refreshLayout.finishRefresh();
        adapter.setNewData(new ArrayList<>());
        emptyCartTipLayout.setVisibility(View.VISIBLE);
        editCB.setVisibility(View.GONE);
        gotoPayLayout.setVisibility(View.GONE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeleteGoods(DeleteGoodsResult result) {
        if (result.getResult() == Flag.Result.SUCCEED) {
            ArrayList<MultipleItemShopCart> oldList = (ArrayList<MultipleItemShopCart>) adapter.getData();
            ArrayList<MultipleItemShopCart> newList = new ArrayList<>(oldList);
            // 从列表中删除已经在服务端删除的item
            //将位置取出到列表中并从大到小排序
            ArrayList<Integer> orderlyPosList = getOrderlyPosList(selectedGoodsArray);
            //根据上一步生成的列表进行删除操作
            for (Integer pos : orderlyPosList) {
                int intPos = pos;
                newList.remove(intPos);
            }
            Log.e(TAG, "onDeleteGoods: newList.size = " + newList.size());
            // 检测是否存在商店中的商品已经全部删除了的商店,有则删除该商店
            ArrayList<Integer> emptyShopList = new ArrayList<>();
            for (int i = newList.size() - 1, length = newList.size(); i > 0; i--) {
                if (newList.get(i).getItemType() == MultipleItemShopCart.SHOP) {
                    if (i == length - 1) {
                        Log.e(TAG, "onDeleteGoods: emptyShopPos = " + i);
                        emptyShopList.add(i);
                    }
                    int lastIndex = i - 1;
                    if (lastIndex >= 0) {
                        if (newList.get(lastIndex).getItemType() == MultipleItemShopCart.SHOP) {
                            Log.e(TAG, "onDeleteGoods: emptyShopPos = " + lastIndex);
                            emptyShopList.add(lastIndex);
                        }
                    }
                }
            }
            if (emptyShopList.size() > 0) {
                for (Integer pos : emptyShopList) {
                    int intPos = pos;
                    newList.remove(intPos);
                }
            }
            adapter.setNewData(newList);
            selectedGoodsArray.clear();
        } else {
            Toast.makeText(getContext(), "喔!删除失败,商品君似乎不想离开购物车",
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEditGoods(EditGoodsEvent event) {
        if (event.isEditStart()) {
            editGoodsArray.put(event.getItemGoods().getId(), new ItemGoodsInShopCart(event.getItemGoods()));
        } else {//完成编辑
            ItemGoodsInShopCart changedItem = editGoodsArray.get(event.getItemGoods().getId());
            if (changedItem != null) {
                if (!changedItem.equals(event.getItemGoods())) {
                    //给后台发送修改请求
                    LatteLogger.e("test", "给后台发送修改请求");
                    ShopCartHandler.updateCartItem(changedItem);
                }
                editGoodsArray.remove(event.getItemGoods().getId());
            }

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEditCount(EditCountEvent event) {
        ItemGoodsInShopCart item = editGoodsArray.get(event.getId());
        if (item != null) {
            item.setTotal(event.isPlusOne() ? item.getTotal() + 1 : item.getTotal() - 1);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateResult(UpdateResult event) {
        if (event.getResult() == Flag.Result.SUCCEED) {
            ShopCartHandler.requestShopCartList();
        } else {
            Toast.makeText(_mActivity, "购物车修改失败", Toast.LENGTH_SHORT).show();
        }
    }

    private ArrayList<Integer> getOrderlyPosList(SparseArray<IdPosBean> sourceArray) {
        TreeSet<Integer> treeSet = new TreeSet<>((Integer o1, Integer o2) -> {
            if (o1 > o2) {
                return -1;
            }
            if (o1 < o2) {
                return 1;
            }
            return 0;
        });
        for (int i = 0, length = sourceArray.size(); i < length; i++) {
            treeSet.add(sourceArray.get(sourceArray.keyAt(i)).getPos());
        }
        return new ArrayList<>(treeSet);
    }

    @Override
    public void onConfirm() {
        //删除勾选的物品
        int size = selectedGoodsArray.size();
        if (size > 0) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < size; i++) {
                sb.append(selectedGoodsArray.keyAt(i));
                if (i != size - 1) {
                    sb.append(",");
                }
            }
            ShopCartHandler.deleteGoodsInCart(sb.toString());
        } else {
            Toast.makeText(getContext(), "您没有勾选商品哟", Toast.LENGTH_SHORT).show();
        }
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    @Override
    public void onCancel() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }


    private SelectParameterDialog specsDialog;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotSpecsData(GotSpecsDataEvent event) {
        if (!isHidden()) {
            if (specsDialog != null) {
                specsDialog.dismiss();
                specsDialog = null;
            }
            specsDialog = new SelectParameterDialog(getContext(), event);
            specsDialog.setType(3);
            specsDialog.setOnShowListener((DialogInterface dialog) -> {
                specsDialog.setSpecs(editGoodsArray.get(SelectParameterDialog.getCartId()));
            });
            specsDialog.show();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onConfirmGoods(ConfirmGoodsEvent event) {
        if (event.getType() == 3) {
            int cartId = SelectParameterDialog.getCartId();
            ItemGoodsInShopCart item = editGoodsArray.get(cartId);
            if (item != null) {
                item.setTotal(event.getItemShopCart().getCount());
                item.setOptionId(event.getItemShopCart().getOptionId());
                item.setOptionTitle(event.getItemShopCart().getOptionTitle());
                item.setHeight(event.getItemShopCart().getHeight());
                item.setWidth(event.getItemShopCart().getWidth());
                item.setCustom(event.getItemShopCart().isCustom());
                int pos = -1;
                for (int i = 0, iLength = adapter.getData().size(); i < iLength; i++) {
                    ItemGoodsInShopCart itemGoodsInShopCart = adapter.getData().get(i).getGoods();
                    if (itemGoodsInShopCart != null) {
                        if (itemGoodsInShopCart.getId() == cartId) {
                            pos = i;
                        }
                    }
                }
                if (pos != -1) {
                    TextView tv = (TextView) adapter.getViewByPosition(pos, R.id.tv_goods_intro_in_edit);
                    if (tv != null) {
                        tv.setText(item.getOptionTitle());
                    }
                    TextView countTv = (TextView) adapter.getViewByPosition(pos, R.id.tv_edit_count);
                    if (countTv != null) {
                        countTv.setText(String.valueOf(item.getTotal()));
                    }
                }
            }
        }
    }
}
